/* ble.c */
#include "ble.h"

volatile uint8_t ble_rx_cmd_cur = 'Z'; /* stop. */

void ble_init(void)
{
    /* disable the connection. */
    GPIO_SetPinsOutputLevel(BOARD_BLE_DISCONNECT_GPIO_PORT, 1u << BOARD_BLE_DISCONNECT_GPIO_PIN, true); /* discon = 1, */
    GPIO_EnablePinsOutputDirection(BOARD_BLE_DISCONNECT_GPIO_PORT, 1u << BOARD_BLE_DISCONNECT_GPIO_PIN, true);
    
    for (uint32_t i = 0u; i < 10000u; i++)
    {
        __asm("nop");
    }
    
    /* setup the uart. */
    UART_Init_Type uart_init;
    uart_init.SrcClkFreq = BOARD_BLE_UART_CLK_SRC_HZ;
    uart_init.Baudrate   = BOARD_BLE_UART_BAUDRATE;
    uart_init.DataBits   = UART_DataBits_8b;
    uart_init.StopBits   = UART_StopBits_1b;
    uart_init.IdleSize   = UART_IdleSize_1B;
    uart_init.Parity     = UART_Parity_None;
    uart_init.TxFifoWatermark = 4u;
    uart_init.RxFifoWatermark = 0u; /* use rx watermark flag as the rx available flag. */
    UART_Init(BOARD_BLE_UART_PORT, &uart_init);
    
    /* enable uart interrupts. */
    NVIC_EnableIRQ(UART0_IRQn);
    UART_EnableInterrupts(BOARD_BLE_UART_PORT, UART_FLAG_RX_REQ);

    /* enable the connect. */
    GPIO_SetPinsOutputLevel(BOARD_BLE_DISCONNECT_GPIO_PORT, 1u << BOARD_BLE_DISCONNECT_GPIO_PIN, false); /* discon = 0. */
}

#if 0
uint8_t ble_getchar(void)
{
    while (0u == (UART_FLAG_RX_REQ & UART_GetStatusFlags(BOARD_BLE_UART_PORT) ) )
    {
    }
    return UART_GetRxFifoData(BOARD_BLE_UART_PORT);
}
#endif

ble_cmd_val_t ble_get_cmd(void)
{
   return (ble_cmd_val_t)ble_rx_cmd_cur;
}

void UART0_IRQHandler(void)
{
    uint32_t flags = UART_GetStatusFlags(BOARD_BLE_UART_PORT) & UART_GetEnabledInterrupts(BOARD_BLE_UART_PORT);
    
    if ( (flags & UART_FLAG_RX_REQ) != 0u )
    {
        ble_rx_cmd_cur = UART_GetRxFifoData(BOARD_BLE_UART_PORT);
        UART_ClearStatusFlags(BOARD_BLE_UART_PORT, UART_FLAG_RX_REQ);
    }
}


/* EOF. */

